package com.qianbei.view;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.qianbei.R;
import com.qianbei.bean.Carbean;
import com.qianbei.bean.GetCarbean;
import com.qianbei.bean.GetCarbean2;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.view.adapter.GetCarAdapter;
import com.qianbei.view.adapter.GetCarBean;
import com.speedata.libuhf.IUHFService;
import com.speedata.libuhf.bean.SpdInventoryData;
import com.speedata.libuhf.interfaces.OnSpdInventoryListener;
import com.tencent.bugly.crashreport.CrashReport;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 取车
 * Dylan
 */

public class GetCarActivity extends BaseActivity {


    TextView che_id, che_time, che_pp, che_xx, che_ys, che_lc, che_gdh;
    /**
     * 当选择不同派车单时 更换派车单对应的车辆信息
     */
    Carbean mode;
    /**
     * 当天驾驶员所有派车单对应的车辆
     */
    List<Carbean> allCar = new ArrayList<Carbean>();
    @Bind(R.id.listView_search_epclist)
    ListView listViewSearchEpclist;
    private int init_progress = 0;
    private PowerManager pM = null;
    private PowerManager.WakeLock wK = null;


    private IUHFService iuhfService;
    GetCarAdapter mAdapter;
    List<GetCarBean> list = new ArrayList<>();

    String tempJobId;
    String tempRouteNo;
    /**
     * 是否上电状态
     */
    private AtomicBoolean isOpenDev = new AtomicBoolean(false);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("gml", "Ocreate------------start");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_getcar_activity);
        ButterKnife.bind(this);
        setTitle("取车");
        mTitle.setrightTitle("扫描");
        initUHFService();
        che_id = (TextView) findViewById(R.id.che_id);
        che_time = (TextView) findViewById(R.id.che_time);
        che_pp = (TextView) findViewById(R.id.che_pp);
        che_xx = (TextView) findViewById(R.id.che_xx);
        che_ys = (TextView) findViewById(R.id.che_ys);
        che_lc = (TextView) findViewById(R.id.che_lc);
        che_gdh = (TextView) findViewById(R.id.che_gdh);
        getListData();

        Log.d("gml", "Ocreate------------start");

        mAdapter = new GetCarAdapter(this, list, R.layout.gufei_item_getcar);
        listViewSearchEpclist.setAdapter(mAdapter);
        listViewSearchEpclist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (GetCarBean bean : mAdapter.getData()) {//全部设为未选中
                    bean.isChecked = false;
                }
                tempJobId = mAdapter.getData().get(position)._id;
                tempRouteNo = mAdapter.getData().get(position).routeNo;
                saveBusinessType(SetData.getJobid());
                GetCarBean checkedJob = mAdapter.getData().get(position);
                //改变要取车辆为派车单对应车辆
                mode = findCarBean(checkedJob);
                updateVehicleTotalKm(mode);
                updateVehicleInfo();
                mAdapter.getData().get(position).isChecked = true;//点击的设为选中
                mAdapter.notifyDataSetChanged();

            }
        });
    }

    private void updateVehicleTotalKm(Carbean mode) {
        if (mode == null) {
            return;
        }
        String totalKm = mode.totalKilometers;
        if (totalKm == null || totalKm.trim().length() == 0) {
            totalKm = "0";
        }
        SetData.setVehicleTotalKm(totalKm);
    }

    /**
     * 更新界面上的车辆信息
     */
    private void updateVehicleInfo() {
        if (mode != null) {
            che_id.setText(mode.vehicleNumber);
            che_pp.setText(mode.vehicleBrand);
            che_xx.setText(mode.vehicleModel);
            che_ys.setText(mode.vehicleColour);
            if (mode.totalKilometers != null) {
                che_lc.setText(mode.totalKilometers + "km");
            }
            if (mode.truckingOrder != null) {
                che_gdh.setText(mode.truckingOrder);
            }
        }
    }

    /**
     * 根据车牌号查找车信息
     *
     * @param checkedJob
     * @return
     */
    private Carbean findCarBean(GetCarBean checkedJob) {
        Carbean car = null;
        for (Carbean oneCar : allCar) {
            if (oneCar.vehicleNumber.equals(checkedJob.vehicle)) {
                car = oneCar;
            }
        }

        return car;
    }

    /**
     * 根据 JobId 设置业务类型 1：医废  2：医塑   3：固废
     *
     * @param jobid
     */
    private void saveBusinessType(String jobid) {
        String jsonString = SetData.getJobs();
        com.alibaba.fastjson.JSONArray jobsAry = JSON.parseArray(jsonString);
        String jobId = SetData.getJobid();

        for (int i = 0; i < jobsAry.size(); i++) {
            com.alibaba.fastjson.JSONObject oneJob = jobsAry.getJSONObject(i);
            String dataJobId = oneJob.getString("_id");
            if (dataJobId.equals(jobId)) {
                int businessType = oneJob.getInteger("businessType");
                SetData.setBusinessType(businessType);
                break;
            }
        }
    }


    private void initUHFService() {
        iuhfService = MyApplication.iuhfService;
        iuhfService.setOnInventoryListener(new OnSpdInventoryListener() {
            @Override
            public void getInventoryData(SpdInventoryData var1) {
                if (!ishow) {
                    handler.sendMessage(handler.obtainMessage(111, var1));
                }
            }
        });

        newWakeLock();
    }

    private void newWakeLock() {
        init_progress++;
        pM = (PowerManager) getSystemService(POWER_SERVICE);
        if (pM != null) {
            wK = pM.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, "lock3992");
            if (wK != null) {
                wK.acquire();
                init_progress++;
            }
        }
        if (init_progress == 1) {
            Log.w("3992_6C", "wake lock init failed");
        }
    }

    boolean ishow = false;
    private Set<String> checked = new HashSet<String>();
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 111:
                    SpdInventoryData var1 = (SpdInventoryData) msg.obj;
                    Log.d("gaoaa", var1.epc);
                    if (mode != null && !ishow && var1.epc.equals(mode.RFID)) {
                        checked.add(var1.epc);
                        ishow = true;
                        show();
                    } else {
                        if (!checked.contains(var1.epc)) {
                            checked.add(var1.epc);
                            new MsgAlert().show("所扫车辆不是派车单分配车辆！");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 上电开串口
     *
     * @return
     */
    private boolean openDev() {
        if (iuhfService.OpenDev() != 0) {
            new android.app.AlertDialog.Builder(this).setTitle(R.string.DIA_ALERT).setMessage(R.string.DEV_OPEN_ERR).setPositiveButton(R.string.DIA_CHECK, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            if (iuhfService != null && isOpenDev.get() == true) {
                iuhfService.newInventoryStop();
                iuhfService.CloseDev();
                //断电后选卡操作会失效，需要重新选卡（掩码）
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @SuppressLint("StaticFieldLeak")
    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.tv_right:
                if (checkSelectOneJob() == false) {
                    new MsgAlert().show("请选择您要收运的路线");
                } else {
                    mTitle.setrightTitle("正在扫描");

                    //重复点扫描按钮时 只做一次上电操作
                    if (isOpenDev.get() == false) {
                        isOpenDev.set(true);
                        new AsyncTask<Void, Void, Void>() {
                            @Override
                            protected Void doInBackground(Void... voids) {
                                try {
                                    if (iuhfService != null) {
                                        if (openDev()) {
                                            isOpenDev.set(false);
                                            return null;
                                        }
                                    }
                                    iuhfService.set_antenna_power(MyApplication.setValue);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    isOpenDev.set(false);
                                    return null;
                                }

                                if (iuhfService == null) {
                                    initUHFService();
                                }
                                iuhfService.newInventoryStart();
                                return null;
                            }
                        }.execute();


                    }
                }

                break;
            default:
                break;
        }
    }

    /**
     * 检查是否选中其中的排车单
     */
    private boolean checkSelectOneJob() {
        boolean selected = false;
        List<GetCarBean> getCardBeans = mAdapter.getData();
        for (GetCarBean bean : getCardBeans) {
            if (bean.isChecked) {
                selected = true;
                break;
            }
        }
        return selected;
    }

    /**
     * 提示用户 绑定
     */
    public void show() {
        AlertDialog dialog = new AlertDialog.Builder(this)
//                .setTitle("是否绑定此车")//设置对话框的标题
                .setMessage("是否绑定此车？")//设置对话框的内容
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                        iuhfService.newInventoryStop();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SetData.setJobid(tempJobId);
                        SetData.setRouteNo(tempRouteNo);
                        checkVehicle();
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }


    /**
     * 获取车辆信息
     *
     * @return
     */

    private void getListData() {
        RequeastBean requeastBean = new RequeastBean("select",
                "com.cygps.dubbo.WasteTransport.IPDAGetVehicle",
                new GetCarbean(SetData.getUserID()));
        ServerControl sc = new ServerControl(requeastBean);
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                Log.d("车辆", "返回: " + sr.toString());
                if (sr.isContinue) {
                    JSONArray js = sr.bodyData.optJSONArray("array");
                    JSONArray li = sr.bodyData.optJSONArray("jobs");
                    JSONArray car = sr.bodyData.optJSONArray("vehicle");
                    JSONObject object = js.optJSONObject(0);
                    mode = JSON.parseObject(object.toString(), Carbean.class);
                    che_id.setText(mode.vehicleNumber);
//                    che_time.setText(mode.qxTime);


                    che_pp.setText(mode.vehicleBrand);
                    che_xx.setText(mode.vehicleModel);
                    che_ys.setText(mode.vehicleColour);
//                    che_lc.setText(mode.totalKilometers + "km");
                    if (mode.totalKilometers != null) {
                        che_lc.setText(mode.totalKilometers + "km");
                    }
                    if (mode.truckingOrder != null) {
                        che_gdh.setText(mode.truckingOrder);
                    }

                    updateVehicleTotalKm(mode);
                    list = JSON.parseArray(li.toString(), GetCarBean.class);
                    for (int i = 0; i < car.length(); i++) {
                        JSONObject oneCar = car.optJSONObject(i);
                        Carbean carBean = JSON.parseObject(oneCar.toString(), Carbean.class);
                        allCar.add(carBean);
                    }

                    mAdapter.addAll(list);
                    mAdapter.notifyDataSetChanged();

                    SetData.setJobs(li.toString());
                } else {
                    if (sr != null && sr.toString().contains("未登录")) {
                        //SetData.setUserID("");
                        SetData.setToken("");
                        finish();
                    }
                }

            }
        };
        new ProgressDialog(mContext).OKpost(sc);
    }

    /**
     * 绑定  车辆和 人
     */
    private void checkVehicle() {

        ServerControl sc = new ServerControl(
                new RequeastBean("checkVehicle", "com.cygps.dubbo.WasteTransport.IPDAGetVehicle",
                        new GetCarbean2(mode.RFID, SetData.getJobid(), mode.vehicleNumber)));
        sc.serverListener = new ServerControl.ServerListener() {

            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    SetData.setCarid(mode.vehicleNumber);
                }
                iuhfService.newInventoryStop();
                finish();

            }
        };
        new ProgressDialog(mContext).OKpost(sc);
    }
}
